package com.googlecode.curvedmetromaps.core.logic.costfunction;

import org.jbox2d.common.Vec2;

import com.googlecode.curvedmetromaps.core.geometry.BasicGeometry;
import com.googlecode.curvedmetromaps.core.model.MetroEdge;
import com.googlecode.curvedmetromaps.core.model.MetroLine;
import com.googlecode.curvedmetromaps.core.model.MetroMap;
import com.googlecode.curvedmetromaps.core.model.MetroStation;

public class ContinuityCost extends BaseCost {

	public ContinuityCost(MetroMap map) {
		super(map);
		createWeight("base", "Base weight", 100);
	}

	@Override
	public String getName() {
		return "Continuity";
	}

	@Override
	public double calculateCost() {
		double result = 0;
		int count = 0;

		for (MetroLine line : map.lines) {
			Vec2 lastCP = null;
			for (int i = 1; i < line.stations.length; i++) {
				MetroStation m1 = line.stations[i - 1];
				MetroStation m2 = line.stations[i];
				MetroEdge edge = map.getEdge(m1, m2);

				Vec2 cp = edge.getCP();

				if (i >= 2) {
					Vec2 p1 = new Vec2(m1.x, m1.y);
					double angle = BasicGeometry.dAngle(lastCP, p1, cp);
					result += Math.abs(angle);
					count++;
				}

				lastCP = cp;
			}
		}

		// Calculate average cost.
		result /= count;
		return getWeight("base") * result;
	}
}
